<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2025-01-21 10:52:26
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-01-21 16:30:59
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\systemSettings\kitchenManage\userConfig\components\addModifPop.vue
-->
<template>
  <pb-popup v-model="isVisible" :title="userForm.userId ? '修改用户' : '添加用户'" @cancelFn="offisVisibleFn"
    @confirmFn="saveFn" :Width="800">
    <el-form :model="userForm" label-width="auto" :inline="true" ref="ruleFormRef" :rules="rules"
      validate-on-rule-change>
      <el-form-item label="账号" prop="loginName">
        <pb-input v-model="userForm.loginName" placeholder="请输入账号" :maxlength="24" :disabled="userForm.userId" />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <pb-input v-model="userForm.userName" placeholder="请输入姓名" :maxlength="20" :disabled="userForm.userId" />
      </el-form-item>
      <el-form-item label="所属食堂" prop="tenantId">
        <pb-select v-model="userForm.tenantId" placeholder="请选择食堂" keys="tenantId" label="tenantName"
          :options="kitchenList" @change="changeKitchen" :disabled="userForm.userId" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <pb-input v-model="userForm.phoneNumber" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="单位">
        <pb-input v-model="userForm.departmentName" placeholder="请输入单位" :maxlength="20" />
      </el-form-item>
      <el-form-item label="职务">
        <pb-input v-model="userForm.postName" placeholder="请输入职务" size="small" :maxlength="20" />
      </el-form-item>


      <el-form-item label="所属角色" prop="roleIds">
        <el-checkbox-group v-model="userForm.roleIds">
          <el-checkbox v-for="(item, index) in roleList" :value="item.roleId" :label="item.roleName" :key="index" />

        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div class="m-t1">默认密码：hao123456</div>
  </pb-popup>
</template>

<script setup lang="ts">
import { getKitchenRole, addKitchenUser, setUserModify, setUserRole } from '@/api/organizeFramework'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";

const props = defineProps(['kitchenList'])

const emits = defineEmits(['refresh'])

const formOrigin = () => ({
  userName: '',
  loginName: '',
  phoneNumber: '',
  departmentName: '',
  postName: '',
  roleIds: [],
  tenantId: '',
})


const userForm = ref(formOrigin())

const rules = reactive({
  loginName: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
    {
      pattern: /^[A-Za-z0-9]{8,24}$/,
      message: "必须为8-24位数字或字母",
      trigger: ["blur", "change"],
    }
  ],
  userName: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
  ],
  // roleIds: [
  //   { required: true, message: "此项必填", trigger: ["blur", "change"] },
  // ],
  tenantId: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
  ],
  phoneNumber: [
    { required: false, pattern: /^1[34578]\d{9}$/, message: "手机号不合法，请重新输入", trigger: ["blur",] },
  ],
})



const isVisible = ref(false)


const showFn = (data) => {
  if (data) {
    userForm.value = data
  } else {
    userForm.value.tenantId = props.kitchenList[0].tenantId
  }
  isVisible.value = true
  getKitchenRoleApi()
}


// 切换食堂
const changeKitchen = (val) => {
  getKitchenRoleApi()
}

const roleList = ref([])
const getKitchenRoleApi = () => {
  return new Promise<void>((resolve, reject) => {
    getKitchenRole({ tenantId: userForm.value.tenantId }).then(res => {
      if (res.code == 2000) {
        roleList.value = res.data
      }
    })
  })
}


const ruleFormRef = ref(null)
const offisVisibleFn = () => {
  isVisible.value = false
  ruleFormRef.value.resetFields();
  userForm.value = formOrigin()
}


const saveFn = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      if (userForm.value.userId) {
        setUserModifyApi()
      } else {
        addKitchenUserApi()
      }
    }
  })
}

// 添加用户
const addKitchenUserApi = () => {
  return new Promise<void>((resolve, reject) => {
    let { roleIds, ...args } = userForm.value
    addKitchenUser(args).then(res => {
      if (res.code == 2000) {
        setUserRoleApi(res.data).then(res => {
          createMessage({
            message: '添加成功',
            type: 'success'
          })
          isVisible.value = false
          emits("refresh")
        })
      }
    })
  })
}
// 修改用户
const setUserModifyApi = () => {
  return new Promise<void>((resolve, reject) => {
    console.log(userForm.value, 88)
    let {
      userId,
      userName,
      postName,
      departmentName,
      phoneNumber,
    } = userForm.value

    let params = {
      userId,
      userName,
      postName,
      departmentName,
      phoneNumber,
    }
    setUserModify(params).then(res => {
      setUserRoleApi().then(res => {
        createMessage({
          message: '修改成功',
          type: 'success'
        })
        isVisible.value = false
        emits("refresh")
      })
    })
  })
}

// 设置用户角色
const setUserRoleApi = (id?: string) => {
  return new Promise<void>((resolve, reject) => {
    let params = {
      userId: id ? id : userForm.value.userId,
      roleIds: userForm.value.roleIds
    }
    setUserRole(params).then(res => {
      if (res.code == 2000) {
        resolve(true)
      }
    })
  })
}



defineExpose({ showFn });
</script>

<style lang="scss" scoped></style>